/**
 * 事件总线 - 用于跨组件通信
 */

// 创建事件容器
class EventBus {
  constructor() {
    this.events = {}
  }

  // 监听事件
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
  }

  // 取消监听
  off(event, callback) {
    if (!this.events[event]) return
    
    if (callback) {
      this.events[event] = this.events[event].filter(cb => cb !== callback)
    } else {
      delete this.events[event]
    }
  }

  // 发送事件
  emit(event, ...args) {
    if (!this.events[event]) return
    
    this.events[event].forEach(callback => {
      callback(...args)
    })
  }

  // 监听一次
  once(event, callback) {
    const onceCallback = (...args) => {
      callback(...args)
      this.off(event, onceCallback)
    }
    this.on(event, onceCallback)
  }

  // 清除所有监听器
  clear() {
    this.events = {}
  }
}

// 创建全局实例
const eventBus = new EventBus()

// 事件类型常量
export const EVENT_TYPES = {
  // 分类相关事件
  CATEGORY_CREATED: 'category:created',
  CATEGORY_UPDATED: 'category:updated',
  CATEGORY_DELETED: 'category:deleted',
  
  // 标签相关事件
  TAG_CREATED: 'tag:created',
  TAG_UPDATED: 'tag:updated',
  TAG_DELETED: 'tag:deleted',
  
  // 用户相关事件
  USER_CREATED: 'user:created',
  USER_UPDATED: 'user:updated',
  USER_DELETED: 'user:deleted',
  
  // 文章相关事件
  ARTICLE_CREATED: 'article:created',
  ARTICLE_UPDATED: 'article:updated',
  ARTICLE_DELETED: 'article:deleted',
  
  // 系统配置更新事件
  CONFIG_UPDATED: 'config:updated',
  
  // 数据刷新事件
  REFRESH_CATEGORIES: 'refresh:categories',
  REFRESH_TAGS: 'refresh:tags',
  REFRESH_USERS: 'refresh:users'
}

// 发送事件
export const emit = (type, data) => {
  eventBus.emit(type, data)
}

// 监听事件
export const on = (type, handler) => {
  eventBus.on(type, handler)
}

// 取消监听
export const off = (type, handler) => {
  eventBus.off(type, handler)
}

// 监听一次
export const once = (type, handler) => {
  eventBus.once(type, handler)
}

// 清除所有监听器
export const clear = () => {
  eventBus.clear()
}

export default {
  emit,
  on,
  off,
  once,
  clear,
  EVENT_TYPES
}